In Java, a class can implement multiple interfaces(multiple inheritance). This is a key feature of Java, as it allows a class to inherit behaviors from multiple sources, which is not possible with class inheritance due to Java’s single inheritance rule.
Here’s how you can implement multiple interfaces in Java:
Multiple interface syntax
class MyClass implements Interface1, Interface2, Interface3 {
// class body
}
In this syntax, MyClass is the class that is implementing the interfaces Interface1, Interface2, and Interface3. The class MyClass must provide implementations for all methods declared in these interfaces.
Here’s an example:
Example of Multiple inheritance using interface in java
// Interface declaration
interface Animal {
void animalName(String name); // interface method
}
// Interface declaration
interface AnimalAction {
void action(String action); // interface method
}
// Class that implements the interface
class Dog implements Animal,AnimalAction {
public void animalName(String name) {
System.out.println("The animal name is: "+ name);
}
public void action(String action) {
System.out.println(action);
}
}
class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Create a Pig object
myDog.animalName("Pug");
myDog.action("Sleeping");
}
}
Output
The animal name is: Pug
Sleeping
In this example, Animal and AnimalAction are interfaces that have methods animalName() and action() respectively. The class Dog implements both Animal and AnimalAction and provides the implementation for these methods.
Remember, implementing multiple interfaces allows a class to inherit multiple behaviors, which can make your code more flexible and powerful.